import React, { useState, useEffect } from "react";
import { Page, Text } from "zmp-ui";
import { useNavigate, useParams } from "react-router-dom";
import { useI18n } from "../i18n";
import { orderApi } from "../api/login";
import { OrderDetailData } from "../types/order";
import Navbar from "../components/navbar";

const OrderDetail: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  
  const [orderDetail, setOrderDetail] = useState<OrderDetailData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');

  // 获取订单详情
  const fetchOrderDetail = async () => {
    if (!id) {
      setError('缺少订单ID参数');
      setLoading(false);
      return;
    }

    setLoading(true);
    setError('');
    
    try {
      const response = await orderApi.getOrderDetail(parseInt(id));
      if (response && response.data) {
        setOrderDetail(response.data);
      } else {
        setError('获取订单详情失败');
      }
    } catch (err: any) {
      console.error('获取订单详情错误:', err);
      setError(err.message || '获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrderDetail();
  }, [id]);

  // 根据后端逻辑判断订单状态
  const getOrderStatus = (order: OrderDetailData): string => {
    if (order.usingStatus === 1) {
      return t("orderDetail.using");
    } else if (order.usingStatus === 2) {
      return t("orderDetail.returned");
    } else if (order.usingStatus === 3) {
      return t("orderDetail.completed");
    } else if (order.usingStatus === 4) {
      return t("orderDetail.purchased");
    } else if (order.usingStatus === 5) {
      return t("orderDetail.repurchased");
    } else {
      return order.usingStausText || t("orderDetail.unknownStatus");
    }
  };

  const getStatusColor = (order: OrderDetailData): string => {
    if (order.usingStatus === 1) {
      return '#FFD700'; // 使用中 - 金黄色
    } else if (order.usingStatus === 2) {
      return '#FF6B6B'; // 已归还 - 红色
    } else if (order.usingStatus === 3) {
      return '#4ECDC4'; // 已完成 - 青色
    } else if (order.usingStatus === 4) {
      return '#FF6B35'; // 已购买 - 橙色
    } else if (order.usingStatus === 5) {
      return '#9B59B6'; // 已回购 - 紫色
    } else {
      return '#666';
    }
  };

  const getStatusDescription = (order: OrderDetailData): string => {
    if (order.usingStatus === 3) {
      return t("orderDetail.completedDescription");
    } else if (order.usingStatus === 1) {
      return t("orderDetail.usingDescription");
    } else if (order.usingStatus === 2) {
      return t("orderDetail.returnedDescription");
    } else if (order.usingStatus === 4) {
      return t("orderDetail.purchasedDescription");
    } else if (order.usingStatus === 5) {
      return t("orderDetail.repurchasedDescription");
    } else {
      return t("orderDetail.processingDescription");
    }
  };

  if (loading) {
    return (
      <Page className="page" style={{ backgroundColor: '#F5F5F7' }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
          <Navbar title={t("orderDetail.title")} />
        </div>
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '60px 20px',
          color: '#666'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '16px' }}>⏳</div>
          <div style={{ fontSize: '16px' }}>{t("orderDetail.loading")}</div>
        </div>
      </Page>
    );
  }

  if (error || !orderDetail) {
    return (
      <Page className="page" style={{ backgroundColor: '#F5F5F7' }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
          <Navbar title={t("orderDetail.title")} />
        </div>
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '60px 20px',
          color: '#666'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '16px' }}>❌</div>
          <div style={{ fontSize: '16px', marginBottom: '8px' }}>{t("orderDetail.loadFailed")}</div>
          <div style={{ fontSize: '14px', color: '#999' }}>{error || t("orderDetail.orderNotFound")}</div>
        </div>
      </Page>
    );
  }

  return (
    <Page className="page" style={{ backgroundColor: '#F5F5F7', padding: 0 }}>
      {/* 顶部导航栏 */}
      <div style={{ position: 'sticky', top: 0, zIndex: 100 }}>
        <Navbar title={t("orderDetail.title")} />
      </div>

      {/* 滚动内容 */}
      <div style={{ 
        height: 'calc(100vh - 60px)',
        overflow: 'auto',
        scrollbarWidth: 'none',
        msOverflowStyle: 'none'
      }}>
        <style>
          {`::-webkit-scrollbar { display: none; }`}
        </style>

        {/* 主要内容卡片 */}
        <div style={{
          backgroundColor: '#fff',
          margin: '12px',
          borderRadius: '12px',
          overflow: 'hidden',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          
          {/* 顶部状态区域 */}
          <div style={{
            padding: '24px 20px',
            textAlign: 'center',
            borderBottom: '1px solid #f0f0f0'
          }}>
            <div style={{
              width: '60px',
              height: '60px',
              borderRadius: '50%',
              backgroundColor: getStatusColor(orderDetail),
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              margin: '0 auto 16px',
              fontSize: '24px',
              color: '#fff'
            }}>
              {orderDetail.usingStatus === 3 ? '✓' : 
               orderDetail.usingStatus === 1 ? '⏱' : 
               orderDetail.usingStatus === 2 ? '⚠' : '✓'}
            </div>
            
            <div style={{
              fontSize: '20px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '8px'
            }}>
              {getOrderStatus(orderDetail)}
            </div>
            
            <div style={{
              fontSize: '14px',
              color: '#666',
              lineHeight: '1.4'
            }}>
              {getStatusDescription(orderDetail)}
            </div>
          </div>

          {/* 订单详情 */}
          <div style={{ padding: '20px' }}>
            <div style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '16px'
            }}>
              {t("orderDetail.orderDetails")}
            </div>
            
            <div style={{ marginBottom: '12px' }}>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.orderNumber")}: {orderDetail.uuid}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.rentalTime")}: {orderDetail.borrowTime}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.rentalLocation")}: {orderDetail.address}
              </div>
              {orderDetail.returnTime && (
                <div style={{
                  fontSize: '14px',
                  color: '#666',
                  marginBottom: '4px'
                }}>
                  {t("orderDetail.returnTime")}: {orderDetail.returnTime}
                </div>
              )}
              {orderDetail.returnTime && (
                <div style={{
                  fontSize: '14px',
                  color: '#666',
                  marginBottom: '4px'
                }}>
                  {t("orderDetail.returnLocation")}: {orderDetail.address}
                </div>
              )}
            </div>
          </div>

          {/* 分割线 */}
          <div style={{ height: '1px', backgroundColor: '#f0f0f0', margin: '0 20px' }} />

          {/* 资费详情 */}
          <div style={{ padding: '20px' }}>
            <div style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '16px'
            }}>
              {t("orderDetail.costDetails")}
            </div>
            
            <div style={{ marginBottom: '12px' }}>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.generatedCost")}: <span style={{ color: '#FF6B35', fontWeight: 'bold' }}>₫ {orderDetail.fee.toFixed(2)}</span>
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.usageDuration")}: {orderDetail.distanceTime}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.billingRules")}: 前30分钟免费, 0.1₫/60分钟, 100000₫/24小时
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {orderDetail.fee.toFixed(2)}₫
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.paymentStatus")}: {orderDetail.is_pay ? t("orderDetail.paid") : t("orderDetail.unpaid")}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.depositMethod")}: {orderDetail.pay_way || 'VNPAY'}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666'
              }}>
                {t("orderDetail.depositAmount")}: {orderDetail.securityFee.toFixed(0)}₫
              </div>
            </div>
          </div>

          {/* 分割线 */}
          <div style={{ height: '1px', backgroundColor: '#f0f0f0', margin: '0 20px' }} />

          {/* 租借设备信息 */}
          <div style={{ padding: '20px' }}>
            <div style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: '#333',
              marginBottom: '16px'
            }}>
              {t("orderDetail.rentalDeviceInfo")}
            </div>
            
            <div style={{ marginBottom: '12px' }}>
              <div style={{
                fontSize: '14px',
                color: '#666',
                marginBottom: '4px'
              }}>
                {t("orderDetail.cabinetSN")}: {orderDetail.box1_device_uuid}
              </div>
              <div style={{
                fontSize: '14px',
                color: '#666'
              }}>
                {t("orderDetail.powerBankSN")}: {orderDetail.single_bank_id}
              </div>
            </div>
          </div>

          {/* 分割线 */}
          <div style={{ height: '1px', backgroundColor: '#f0f0f0', margin: '0 20px' }} />

          {/* 归还设备信息 */}
          {orderDetail.returnTime && (
            <div style={{ padding: '20px' }}>
              <div style={{
                fontSize: '16px',
                fontWeight: 'bold',
                color: '#333',
                marginBottom: '16px'
              }}>
                {t("orderDetail.returnDeviceInfo")}
              </div>
              
              <div style={{ marginBottom: '12px' }}>
                <div style={{
                  fontSize: '14px',
                  color: '#666'
                }}>
                  {t("orderDetail.cabinetSN")}: {orderDetail.box1_device_uuid}
                </div>
              </div>
            </div>
          )}

          {/* 底部收起按钮 */}
          <div style={{
            padding: '12px 20px',
            textAlign: 'center',
            borderTop: '1px solid #f0f0f0',
            backgroundColor: '#fafafa'
          }}>
            <div style={{
              fontSize: '14px',
              color: '#666',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer'
            }}>
              {t("orderDetail.collapse")} <span style={{ marginLeft: '4px' }}>⌄</span>
            </div>
          </div>
        </div>
      </div>
    </Page>
  );
};

export default OrderDetail;